﻿using LbangCMS.Areas.Admin.Models;
using LbangCMS.EFModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LbangCMS.Areas.Admin.Controllers
{
    [Authorize]
    public class SinglePageController : Controller
    {
        public ActionResult EditPage(string code)
        {
            var page = GetPage(code);
            if(page!=null)
            {
                var model = new SinglePageModel();
                model.Body = page.Body;
                model.Title = page.Title;
                model.Code = page.Code;
                return View(model);
            }
            else
            {
                return Content("内容不存在");
            }
            
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult EditPage(string code,string body)
        {
            SaveSinglePage(code, body);
            return Json(new { success = true });
        }

        private SinglePage GetPage(string code)
        {
            using (var db = new Database())
            {
                return db.SinglePages.Where(o => o.Code == code).FirstOrDefault();
            }
        }

        private void SaveSinglePage(string code,string body)
        {
            using (var db = new Database())
            {
                var page = db.SinglePages.Where(o => o.Code == code).FirstOrDefault();
                if(page!=null)
                {
                    page.Body = body;
                    db.SaveChanges();
                }
            }
        }
    }
}